package com.smart.campus.web.controller.school;

import java.util.*;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.smart.campus.common.utils.DateUtils;
import com.smart.campus.school.domain.ClassInfo;
import com.smart.campus.school.domain.WrongQuestion;
import com.smart.campus.school.domain.request.CreateStudentNoRequest;
import com.smart.campus.school.domain.request.StudentNoRequest;
import com.smart.campus.school.service.IClassInfoService;
import com.smart.campus.school.service.IGradeService;
import com.smart.campus.web.utils.SchoolUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.smart.campus.common.annotation.Log;
import com.smart.campus.common.enums.BusinessType;
import com.smart.campus.school.domain.Student;
import com.smart.campus.school.service.IStudentService;
import com.smart.campus.common.core.controller.BaseController;
import com.smart.campus.common.core.domain.AjaxResult;
import com.smart.campus.common.utils.poi.ExcelUtil;
import com.smart.campus.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 学生信息Controller
 * 
 * @author Zhihe.Li
 * @date 2020-05-18
 */
@Controller
@RequestMapping("/school/student")
public class StudentController extends BaseController
{
    private String prefix = "school/student";

    @Autowired
    private IStudentService studentService;

    @Autowired
    private IGradeService gradeService;

    @Autowired
    private IClassInfoService classInfoService;

    @RequiresPermissions("school:student:view")
    @GetMapping()
    public String student()
    {
        return prefix + "/student";
    }

    /**
     * 查询学生信息列表
     */
    @RequiresPermissions("school:student:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Student student)
    {
        startPage();
        List<Student> list = studentService.selectStudentList(student);
        return getDataTable(list);
    }

    /**
     * 导出学生信息列表
     */
    @RequiresPermissions("school:student:export")
    @Log(title = "学生信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Student student)
    {
        List<Student> list = studentService.selectStudentList(student);
        ExcelUtil<Student> util = new ExcelUtil<Student>(Student.class);
        return util.exportExcel(list, "student");
    }

    /**
     * 新增学生信息
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存学生信息
     */
    @RequiresPermissions("school:student:add")
    @Log(title = "学生信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Student student)
    {
        return toAjax(studentService.insertStudent(student));
    }

    /**
     * 修改学生信息
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        Student student = studentService.selectStudentById(id);
        mmap.put("student", student);
        return prefix + "/edit";
    }

    /**
     * 修改保存学生信息
     */
    @RequiresPermissions("school:student:edit")
    @Log(title = "学生信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Student student)
    {
        return toAjax(studentService.updateStudent(student));
    }

    /**
     * 删除学生信息
     */
    @RequiresPermissions("school:student:remove")
    @Log(title = "学生信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(studentService.deleteStudentByIds(ids));
    }



    /**
     * 查询学生信息列表
     */
    @GetMapping("/getStudent")
    @ResponseBody
    public TableDataInfo getStudent(Student student)
    {
        startPage();
        List<Student> list = studentService.selectStudentList(student);
        return getDataTable(list);
    }

    /**
     * 通用学生查询
     * @return
     */
    @GetMapping("query")
    public String query()
    {
        return prefix + "/query";
    }

    /**
     * 生成学号
     * @return
     */
    @RequiresPermissions("school:student:createStudentNo")
    @GetMapping("createStudentNo")
    public String createStudentNo(ModelMap mmap)
    {
        ClassInfo classInfo = new ClassInfo();
        classInfo.setDeptId(SchoolUtil.getSchoolId());
        classInfo.setComeYear(DateUtils.getCurrentYear());
        List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(classInfo);
        mmap.put("year", DateUtils.getCurrentYear());
        if(CollectionUtils.isNotEmpty(classInfoList)){
            mmap.put("classList", classInfoList);
            mmap.put("studentCount", studentService.getStudentCountByClassIdList(classInfoList.stream().map(ClassInfo::getId).collect(Collectors.toList())));
        }
        return prefix + "/studentNo";
    }

    /**
     * 修改保存学生学号
     */
    @RequiresPermissions("school:student:createStudentNo")
    @Log(title = "学生学号", businessType = BusinessType.UPDATE)
    @PostMapping("/createStudentNoSave")
    @ResponseBody
    public AjaxResult createStudentNoSave(CreateStudentNoRequest request)
    {
        List<StudentNoRequest> classCode = request.getStudentNoRequestList();

        for (StudentNoRequest studentNoRequest : classCode) {
            Student student = new Student();
            student.setStatus(1);
            student.setClassId(studentNoRequest.getClassId());
            List<Student> studentList = studentService.selectStudentList(student);
            if(CollectionUtils.isNotEmpty(studentList)){
                Collections.sort(studentList, (a, b) -> b.getComeScore().compareTo(a.getComeScore()));
                for (int i = 0; i < studentList.size(); i++) {
                    Student st = studentList.get(i);
                        st.setStudentNo(request.getPrefix()+studentNoRequest.getStudentBatchNo()+ String.format("%03d",i+1));
                    studentService.updateStudent(st);
                }

            }
        }


        return toAjax(1);
    }

    /**
     * 根据入学年份获取所选班级列表
     * @return
     */
    @RequiresPermissions("school:student:createStudentNo")
    @GetMapping("getClassListByComeYear")
    @ResponseBody
    public Map<String,Object> getClassListByComeYear(String comeYear)
    {

        Map<String,Object> map = new HashMap<>();
        ClassInfo classInfo = new ClassInfo();
        classInfo.setDeptId(SchoolUtil.getSchoolId());
        classInfo.setComeYear(comeYear);
        List<ClassInfo> classInfoList = classInfoService.selectClassInfoList(classInfo);
        if(CollectionUtils.isNotEmpty(classInfoList)){
            map.put("classList", classInfoList);
            map.put("studentCount", studentService.getStudentCountByClassIdList(classInfoList.stream().map(ClassInfo::getId).collect(Collectors.toList())));
        }
        return map;
    }

    @Log(title = "学生", businessType = BusinessType.IMPORT)
    @RequiresPermissions("school:student:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<Student> util = new ExcelUtil<Student>(Student.class);
        List<Student> list = util.importExcel(file.getInputStream());

        for (Student student : list) {
            studentService.insertStudent(student);
        }

        return AjaxResult.success("导入成功");
    }


    @RequiresPermissions("school:student:import")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<Student> util = new ExcelUtil<Student>(Student.class);
        return util.importTemplateExcel("学生数据");
    }


    /**
     * 根据id查询学生
     */
    @GetMapping("/getStudentByClassId")
    @ResponseBody
    public List<Student> getStudentByClassId(Student student)
    {
        List<Student> list = studentService.selectStudentList(student);
        return list;
    }
}



